from api import CandidateState, ImEditor


class Editor(ImEditor):
    def __init__(self, candidate_state: CandidateState, config=None) -> None:
        super().__init__()
        print('>>> create Editor')
        self.cs = candidate_state
        self.alphabet = 'qwertyuiopasdfghjklzxcvbnm'
        self.initials = 'qwertyuiopasdfghjklzxcvbnm'
        self._maxLength = 64
        self.lengthOverflow = 'reject'
        self._applyConfig(config)

    def accept(self, code: str) -> bool:
        ok = False
        oldInput = self.cs.composition
        length = len(oldInput)
        if length == 0:
            ok = code in self.initials
        elif length < self._maxLength:
            ok = code in self.alphabet
        else:
            if self.lengthOverflow == 'reject':
                ok = False
            elif self.lengthOverflow == 'clear':
                self.clear()
                ok = True
            elif self.lengthOverflow == 'accept':
                self.cs.composition += code
                ok = False
        if ok and oldInput == self.cs.composition:
            self.cs.composition += code
        return ok

    def maxLength(self) -> int:
        return self._maxLength

    def backspace(self):
        if self.cs.hasComposition():
            self.cs.composition = self.cs.composition[0:-1]

    def clear(self):
        self.cs.reset()

    def _applyConfig(self, config):
        if config is None:
            return
        if 'alphabet' in config:
            self.alphabet = config.get('alphabet')
        if 'initials' in config:
            self.initials = config.get('initials')
        if 'maxLength' in config:
            self._maxLength = config.get('maxLength')
        if 'lengthOverflow' in config:
            self.lengthOverflow = config.get('lengthOverflow')
